package czk.concrent.juc.countDOwnLatch.practice;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 多个资源等待一个资源
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/23 15:46
 */
public class MostSourceWaitOneSource {
    public static void main(String[] args) {
        System.out.println("开始准备");
        CountDownLatch downLatch = new CountDownLatch(1);
        new Thread(new RunMan(downLatch), "小明").start();
        new Thread(new RunMan(downLatch), "小滑").start();
        new Thread(new RunMan(downLatch), "小六").start();
        try {
            Thread.sleep(2000);
            System.out.println("裁判员开枪。。。。");
            // 这里开始发枪
            downLatch.countDown();
            Thread.sleep(2000);
            System.out.println("比赛结束");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

class RunMan implements Runnable {
    private CountDownLatch latch;

    public RunMan(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        System.out.println("运动员：" + Thread.currentThread() + "准备完毕，等待发枪");
        try {
            latch.await();
            TimeUnit.MILLISECONDS.sleep((int) Math.random() * 1000);
            System.out.println("运动员【" + Thread.currentThread().getName() + "】到达终点");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
